<?php

namespace yak\layui\behaviors;

use Yii;
use yak\layui\widgets\grid\LayuiListData;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\web\HeaderCollection;
use yii\web\Request;
use yii\web\Response;

class LayuiExcelDataBehavior extends LayuiBehavior
{
    /**
     * @var array
     */
    protected $columns;

    /**
     * @var ActiveDataProvider
     */
    protected $dataProvider;


    protected $maxLimit = 10000;


    public function run(HeaderCollection $headers, Request $request, array $params, Response $response)
    {
        // TODO: Implement run() method.
        $searchClass = $headers->get('Search-Class', null);
        if ($searchClass === null) {
            return $this->fail('class model not found!!');
        }

        $searchModel = Yii::createObject($searchClass);
        $this->dataProvider = $searchModel->search($params['Condition']);
        $this->columns = $searchModel->outputColumns();

        return $this->result();
    }

    protected function result()
    {
        try {

            $pagination = new Pagination();
            $pagination->setPage(0);
            $pagination->setPageSize($this->maxLimit);
            $this->dataProvider->setPagination($pagination);

            $dataView = new LayuiListData([
                'dataProvider' => $this->dataProvider,
                'columns' => $this->columns
            ]);

            return $this->successExcel($dataView->renderData(),
                $dataView->renderHeader());

        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

}